<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>View Message</title>
</head>
<body>
<%@ page import="tuna.Process" %>
<%@ page import="tuna.DBConnection" %>
<%@ page import="java.sql.ResultSet;" %>
<%
	String day = request.getParameter("day");
	String us = request.getParameter("us");
	String role = request.getParameter("role");
	String id = request.getParameter("id");
	String senderId = request.getParameter("senderId");
	String senderUtorId = request.getParameter("senderUtorId");
	
	if(Process.validate(day, us, role, id) && (senderId != null || !senderId.isEmpty()) && 
			(senderUtorId != null || !senderUtorId.isEmpty())) {
		String parameters = "?day=" + day + "&us=" + us + "&role=" + role + "&id=" + id + 
				"&senderId=" + senderId + "&senderUtorId=" + senderUtorId;
%>
	<table align="center" style="font-family: arial; width: 480px;">
		<tr>
			<td>
				Messages from <%= senderUtorId %>
			</td>
			<td>
				<input type="button" value="Compose Message" onclick="location.href='/tuna/composeMessage.jsp<%= parameters %>'" />
			</td>
		</tr>
		<tr>
			<td colspan=2>
				&nbsp;
			</td>
		</tr>
		<tr>
			<td colspan=2>
				<table>
					<tr>
						<td>					
							Message
						</td>
						<td>
							Time
						</td>
					</tr>
				<% 
					//Create DB connection & connect
				    DBConnection dbCon = new DBConnection("localhost:3306", "tuna", "root", "asdf1234");
				    dbCon.connectDB();

				    //Retrieve result set
				    String query = "select detail, sentAt from tuna.msgRecord where senderId=" + senderId +
				    " and receiverId=" + id + " order by sentAt asc";
				    
				    ResultSet latestMsg = dbCon.runQuery(query);	
				    
				    while(latestMsg.next()) {
						String detail = latestMsg.getString(1);
						String sentAt = latestMsg.getString(2);
				%>		
					<tr>
						<td>
							<%= detail %>
						</td>
						<td>
							<%= sentAt %>
						</td>
					</tr>
				<%	
				    }
				    
				    dbCon.disconnectDB();
				%>
				</table>
			</td>
		</tr>	
	</table>
<% 
	}
	else {
		response.sendRedirect("/tuna/login.jsp");
	}
%>
</body>
</html>